
const arc_face = require('./face_engine');
const path = require('path');
const config = require('./config');
const m = require('./logger');
const client = require('./clients');
const imageHelper = require('./face_cv_image');
const fsUtil = require('./fileUtils');

// 设置dll路径
let dllPath = "";
if (process.env.NODE_ENV !== 'development') {
    dllPath = require('path').join(__dirname, '../../main/lib/X64').replace(/\\/g, '\\\\')
}else{
    dllPath = require('path').join(__dirname, '../lib/X64').replace(/\\/g, '\\\\')
}

console.log("dllPath",dllPath);
// 添加DLL所在目录到环境变量
process.env['PATH'] = `${process.env.PATH};${dllPath}`;

// 初始化接口
const arc = new arc_face(config.lib_win64);

Object.prototype.toString = function(){
    return JSON.stringify(this);
};

Date.prototype.toLocaleString = function() {
    return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds();
};

this.test_arc = async () => {
    try{
        let dataInfo = arc.getActiveFileInfo();
        if (null != dataInfo){
            let start = new Date(parseInt(dataInfo.startTime) * 1000);
            let end = new Date(parseInt(dataInfo.endTime) * 1000);

            m.logger.info("expire date is from %s to %s, please check the date for expired.thank you.",
                start.toLocaleString(),
                end.toLocaleString()
            );

            if (new Date().getTime() > end){
                m.logger.warn('your arc soft is expired,please change the file to continue use it,thank you.');
                return;
            }
        }
        client.get('active', (err, res) => {
            // 激活
            if (!res || parseInt(res) !== 1){
                let ib = arc.activeFaceEngine(config.appId,config.appKey);
                client.set('active',ib?1:0);
            }else{
                m.logger.info("engine has already initialed, do not repeat active");
            }
        });

        let version = arc.getVersion();
        m.logger.info("current verson is %s",version.Version);

        // 初始化引擎
        arc.initialFaceEngine(16,50);

        // 设置可信度
        arc.setLiveParam(0.5,0.7);

        let img_path1 = path.join(__dirname, './img/1.jpg');
        let img_path2 = path.join(__dirname, './img/2.jpg');
        let img_path3 = path.join(__dirname, './img/3.jpg');


        // opencv 处理图片
        let asvl1 = await imageHelper.cvImages(img_path1,false,path.join(__dirname, './img/test'));
        let asvl2 = await imageHelper.cvImages(img_path2,false,path.join(__dirname, './img/test'));
        let asvl3 = await imageHelper.cvImages(img_path3,false,path.join(__dirname, './img/test'));

        // jimp 处理图片
        // let asvl1 = await imageHelper.parseImage(img_path1,false);
        // let asvl2 = await imageHelper.parseImage(img_path2,false);
        // let asvl3 = await imageHelper.parseImage(img_path3,false);

        // 检测人脸
        let data1 = arc.detectFacesEx(asvl1.imageData);
        let data2 = arc.detectFacesEx(asvl2.imageData);

        // 提取特征值
        let feature1 = arc.extractFeature(asvl1.imageData, data1.multi.faceRect[0], data1.multi.faceOrient[0]);
        let feature2 = arc.extractFeature(asvl2.imageData, data2.multi.faceRect[0], data2.multi.faceOrient[0]);

        if (!feature1 || !feature2){
            m.logger.error("feature1 or feature2 is null. please check.");
            return;
        }

        // console.log("feature1",feature1)
        // console.log("feature2",feature2)

        // 比较
        let sim = arc.compareFeature(feature1.nav,feature2.nav);
        if (sim < 0){
            m.logger.info("similar is %d,is not the same person.",sim);
            return;
        }
        if (sim > 0.8){
            m.logger.info("similar is %d,is the same person.",sim);
        }else{
            m.logger.info("similar is %d,is not the same person.",sim);
        }
        // base64 转 feature 测试 ，实际效果会差0.02
        let f1 = arc.base64ToFeature(feature1.nab.featureBuffer);
        let f2 = arc.base64ToFeature(feature2.nab.featureBuffer);
        let ff = arc.compareFeature(f1,f2);

        if (ff > 0.8){
            m.logger.info("similar is %d,is the same person.",ff);
        }else{
            m.logger.info("similar is %d,is not the same person.",ff);
        }

        // 释放人脸指针
        arc.release(f1.feature);
        arc.release(f2.feature);

        // 单体检测
        let ib = arc.processEx(asvl3.imageData,false);
        if (!ib){
            m.logger.error("single process checked failed.");
            return;
        }
        arc.getSexInfo();

        arc.getAgeInfo();

        arc.getAngleInfo();

        arc.getLivenessScore(false);

        // // 测试画框

        let isIR = false;
        // let asvl5 = await imageHelper.cvImages(img_path1,isIR);
        // let info = arc.detectFacesEx(asvl5.imageData);
        // console.log('info',info);

        // let filePath = path.join(__dirname, './img/faces');
        // await fsUtil.dirExists(filePath);
        // imageHelper.drawFace(img_path1,info.multi,true,filePath);

        let fileCv = path.join(__dirname, './img/faces');
        await fsUtil.dirExists(fileCv);
        let asvl6 = await imageHelper.cvImages(img_path1,isIR,fileCv);
        let faces = arc.detectFaces(asvl6,false);
        // console.log('faces',faces);

        let info = arc.processNone(asvl6,false);
        arc.getLivenessScore(false);

        // console.log('info',info);

        // 释放 函数中已经释放调用的指针
        arc.unInitialEngine();
        client.quit();
    }catch (e) {
        m.logger.info("test_arc some error happened.%o",e);
        arc.unInitialEngine();
        client.quit()
    }
};

this.test_arc();











